package com.amumu.drama.portal.util;

import com.amumu.drama.common.exception.ApiException;
import com.amumu.drama.model.UmsMember;
import com.amumu.drama.portal.domain.MemberDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author sunzhuang
 * @date 2024/5/24 16:05
 * @slogan 天下风云出我辈, 一入代码岁月催
 * @desc todo
 */

public class MemberUtil {
    public static UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        Object principal = auth.getPrincipal();
        if (!(principal instanceof MemberDetails)) {
            throw new ApiException("未登录或登录已过期");
        }
        MemberDetails memberDetails = (MemberDetails) principal;
        if (memberDetails == null || memberDetails.getUmsMember() == null) {
            throw new ApiException("未登录或登录已过期");
        }
        return memberDetails.getUmsMember();
    }

    public static Long getCurrentMemberId() {
        return getCurrentMember().getId();
    }
}
